// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import {
  DOREQUESTEDUCATIONINFORMATION,
  DOREQUESTESUBMIT,
  DOREQUESTEEDITEDU
} from './store/actions/pageeducationinformation'
import {
  CLEARPAGEEDUCATIONINFORMATION,
  UPDATEPAGEEDUCATIONINFORMATION
} from './store/types/pageeducationinformation'
import { UPDATEPAGECHOOSEJOBINPUT } from '../../pages/choose-job-input/store/types/pagechoosejobinput'

// less
import './index.less'
import NetworkError from '../../components/taro-ui/network-error'
import { showLoading, hideLoading, showToast } from '../../crossplatform/apiservice/toast'
import MessageSelectSingle from '../../components/page-components/message-select-single'
import { deepCopy } from '../../util/lodashmin'
import MessageInputWrap from '../../components/page-components/message-input-wrap'
import BtmFixedBtn from '../../components/page-components/btm-fixed-btn'
import BtnFixedDelete from '../../components/page-components/btn-fixed-delete'
import { navigateTo, navigateBack } from '../../crossplatform/apiservice/navigate'
import { putDeleteEducationRequest } from '../../service/user-archive-controller'
import pagejumplist from '../../configuration/pagejumplist.json'
import { judyCanLight } from '../../util/pagemethods/judyThings'
import If from '../../components/page-components/if'
import Dialog from '../../components/page-components/dialog'

const mapActiontoProps = dispatch => ({
  updateState (payload) {
    dispatch({
      type: UPDATEPAGEEDUCATIONINFORMATION,
      payload: {
        ...payload
      }
    })
  },
  clearState () {
    dispatch({
      type: CLEARPAGEEDUCATIONINFORMATION
    })
  },
  updateJobInput (payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  },
  dorequest (payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTEDUCATIONINFORMATION(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  submit (payload) {
    DOREQUESTESUBMIT(payload).then(({ status, message }) => {
      if (status) {
        showToast({
          title: '创建成功！'
        })
        setTimeout(() => {
          navigateBack()
        }, 500)
      } else {
        showToast({
          title: message || '创建失败！'
        })
      }
    })
  },
  editeducation (payload) {
    DOREQUESTEEDITEDU(payload).then(({ status, message }) => {
      if (status) {
        showToast({
          title: '编辑成功！'
        })
        setTimeout(() => {
          navigateBack()
        }, 500)
      } else {
        showToast({
          title: message || '编辑失败！'
        })
      }
    })
  }
})

@connect(
  ({
    pageeducationinformation,
    userinfo,
    pageneweducationainformation,
    pagecreatecompany,
    pagechoosejobinput
  }) => ({
    ...pageeducationinformation,
    educationInformation: pageneweducationainformation.educationInformation,
    zhichuUserId: userinfo.zhichuUserId,
    userId: userinfo.userId,
    jobinput: pagechoosejobinput.inputData,
    schoolName: pagecreatecompany && pagecreatecompany.schoolName,
    shouldGetSchool: pagecreatecompany && pagecreatecompany.shouldGetSchool
  }),
  mapActiontoProps
)
class EducationInformation extends Component {
  constructor (props) {
    this.state = { modalVisible: false }
  }

  config = {
    navigationBarTitleText: '教育信息'
  }

  componentWillMount () {
    // onLoad
    let { id } = this.$router.params
    this.props.updateState({
      submitid: id
    })
    if (id) {
      this.props.updateState({
        cant: false
      })
    } else {
      this.props.updateState({
        cant: true
      })
    }
    this.queryWrap()

    this.setState({
      modalVisible: false
    })
  }

  componentDidMount () {
    // onready
  }

  componentDidShow () {
    // onshow
    if (this.props.shouldGetSchool) {
      const { schoolName } = this.props
      this.onShowChangeSchool({ value: schoolName })
    }
    this.doOnShowInput && this.doOnShowInput()
    this.doOnShowInput = null
  }

  componentDidHide () {
    // onhide
  }

  componentWillUnmount () {
    // onUnload
    this.props.clearState()
  }

  queryWrap = () => {
    const { submitid: id } = this.props
    if (id) {
      let { educationInformation } = this.props
      let singledata
      educationInformation.forEach(data => {
        if (data.id == id) {
          singledata = data
        }
      })
      if (singledata) {
        this.setInitData(singledata)
      }
    } else {
      let nowYear = new Date().getFullYear()
      this.props.updateState({
        dateInWrap: {
          mode: 'date',
          value: '2015'
        },
        dateOutWrap: {
          mode: 'date',
          value: nowYear + ''
        },
        schoolWrap: {
          value: ''
        }
      })
    }
  }

  setInitData = singledata => {
    let {
      schoolWrap,
      degreeSource,
      degreeList,
      degreeValue,
      dateInWrap,
      dateOutWrap,
      nowStatusWrap
    } = this.props

    degreeList = [...degreeSource]
    // degreeList.pop() // 删掉 学历不限
    degreeValue = singledata.course

    let nowStatusWrapValue = '0'
    if (nowStatusWrap.list) {
      nowStatusWrap.list.forEach((data, index) => {
        if (data.name == singledata.attributes) {
          nowStatusWrapValue = index
        }
      })
    }
    this.props.updateState({
      professionalname: singledata.professional,
      schoolWrap: {
        ...schoolWrap,
        value: singledata.schoolname
      },
      degreeList,
      degreeValue,
      dateInWrap: {
        ...dateInWrap,
        value: singledata.time && singledata.time.split('-')[0].trim()
      },
      dateOutWrap: {
        ...dateOutWrap,
        value: singledata.time && singledata.time.split('-')[1].trim()
      },
      nowStatusWrap: {
        ...nowStatusWrap,
        value: nowStatusWrapValue
      }
    })
  }

  onReload = () => {
    this.queryWrap()
  }

  onShowChangeSchool = ({ value }) => {
    const schoolWrap = deepCopy(this.props.schoolWrap)
    schoolWrap.value = value
    this.props.updateState({
      schoolWrap: schoolWrap
    })
  }

  onChange = ({ type, value, column }) => {
    if (type == 'schoolname') {
      const schoolWrap = deepCopy(this.props.schoolWrap)
      schoolWrap.value = value
      this.props.updateState({
        schoolWrap: schoolWrap
      })
      navigateTo({
        url: `${pagejumplist['create-company'].path}?pageType=school`
      })
    } else if (type == 'degree') {
      const education = this.props.degreeList[value].value
      this.props.updateState({
        degreeValue: education
      })
    } else if (type == 'datein') {
      const dateInWrap = deepCopy(this.props.dateInWrap)
      dateInWrap.value = value
      this.props.updateState({
        dateInWrap: dateInWrap
      })
    } else if (type == 'dateout') {
      const dateOutWrap = deepCopy(this.props.dateOutWrap)
      dateOutWrap.value = value
      this.props.updateState({
        dateOutWrap: dateOutWrap
      })
    } else if (type == 'nowstatus') {
      const nowStatusWrap = deepCopy(this.props.nowStatusWrap)
      nowStatusWrap.value = value
      this.props.updateState({
        nowStatusWrap: nowStatusWrap
      })
    }
    this.judyCanLight()
  }
  doOnShowInput = null

  onInputChange = ({ type, value, name, componenttype, maxLength, tip }) => {
    this.doOnShowInput = () => {
      if (type == 'school') {
        this.props.updateState({
          schoolWrap: {
            value: this.props.jobinput.value
          }
        })
      } else {
        this.props.updateState({
          professionalname: this.props.jobinput.value
        })
      }
      this.judyCanLight()
    }
    this.props.updateJobInput({
      inputData: { type, value, name, componenttype, maxLength, tip }
    })
    navigateTo({
      url: `${pagejumplist['choose-job-input'].path}?pageType=major`
    })
  }

  delay (time = 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  formatSubmitData = () => {
    const {
      zhichuUserId,
      professionalname,
      schoolWrap,
      degreeValue,
      dateInWrap,
      dateOutWrap,
      nowStatusWrap
    } = this.props
    return {
      attributes: nowStatusWrap.list[nowStatusWrap.value].name,
      beginTime: dateInWrap.value.trim(),
      degreeLevel: degreeValue,
      endTime: dateOutWrap.value.trim(),
      majorName: professionalname,
      schoolName: schoolWrap.value,
      userId: zhichuUserId
    }
  }

  judyCanLight = () => {
    const result = this.formatSubmitData()
    let expect = {
      attributes: '',
      beginTime: '',
      degreeLevel: '',
      endTime: '',
      majorName: '',
      schoolName: ''
    }
    let canlight = judyCanLight(result, expect)
    this.props.updateState({
      cant: !canlight
    })
  }

  onTap = () => {
    const { submitid, zhichuUserId } = this.props
    const result = this.formatSubmitData()
    if (!this.jugdyResult(result)) {
      // 数据格式失败  重新填写
      return
    }
    if (submitid) {
      this.props.editeducation({ ...result, id: submitid, userId: zhichuUserId })
    } else {
      this.props.submit(result)
    }
  }

  jugdyResult = result => {
    // 检测数据问题
    const { beginTime, endTime } = result
    const nowYear = new Date().getFullYear()
    if (beginTime > endTime) {
      showToast({
        title: '开始时间不能大于结束时间'
      })
      return false
    } else if (beginTime > nowYear) {
      showToast({
        title: '不能大于当前年份'
      })
      return false
    }
    return true
  }

  onDelete = () => {
    // 点击删除按钮
    this.setState({
      modalVisible: true
    })
  }

  onDeleteCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  onDeleteOk = () => {
    const { id } = this.$router.params
    const { educationInformation, userId } = this.props
    if (educationInformation && educationInformation.length > 1) {
      showLoading()
      putDeleteEducationRequest({ id, userId }).then(({ data }) => {
        hideLoading()
        if (data.status) {
          // 删除成功 返回上一个页面
          showToast({
            title: '删除成功'
          })
          setTimeout(() => {
            navigateBack()
          }, 500)
        } else {
          showToast({
            title: data.message || '删除失败'
          })
        }
      })
    } else {
      this.setState({
        modalVisible: false
      })
      showToast({
        title: '当前为最后一条教育信息， 无法删除'
      })
    }
  }

  render () {
    const { submitid, educationInformation } = this.props
    const { modalVisible } = this.state
    return (
      <View className="EducationInformation_id48869">
        <NetworkError visible={this.props.networkerror} onReload={this.onReload} />
        <View
          className={`EducationInformation_id48869Wrap ${this.props.networkerror ? 'hide' : ''}`}
        >
          <View className="title">教育信息</View>
          <MessageSelectSingle
            name="学校名称"
            type="schoolname"
            value={this.props.schoolWrap.value}
            onChange={this.onChange}
          />
          <MessageSelectSingle
            type="degree"
            name="学历"
            value={this.props.degreeValue}
            selectlist={this.props.degreeList}
            onChange={this.onChange}
          />
          <MessageInputWrap
            name="专业"
            componenttype="input"
            value={this.props.professionalname}
            onChange={this.onInputChange}
            tip="*输入你所学习的专业名称"
            maxLength="16"
          />
          <MessageSelectSingle
            name="入学年份"
            type="datein"
            fields="year"
            start="1900-01-01"
            end="2100-01-01"
            value={this.props.dateInWrap.value}
            mode={this.props.dateInWrap.mode}
            selectlist={this.props.dateInWrap.list}
            onChange={this.onChange}
          />
          <MessageSelectSingle
            name="毕业年份"
            type="dateout"
            fields="year"
            start="1900-01-01"
            end="2100-01-01"
            value={this.props.dateOutWrap.value}
            mode={this.props.dateOutWrap.mode}
            selectlist={this.props.dateOutWrap.list}
            onChange={this.onChange}
          />
        </View>
        <If visible={!submitid}>
          <BtmFixedBtn text="保存" onTap={this.onTap} cant={this.props.cant} />
        </If>
        <If visible={submitid}>
          <BtnFixedDelete
            leftText={`${educationInformation && educationInformation.length > 1 ? '删除' : ''}`}
            rightText="保存"
            onDelete={this.onDelete}
            onTap={this.onTap}
            cant={this.props.cant}
          />
        </If>
        <AtActionSheet isOpened={modalVisible}>
          <Dialog
            title="温馨提示"
            subtext="您确定要删除此段教育经历吗？"
            leftText="取消"
            rightText="确认"
            onOk={this.onDeleteOk}
            onLeftOk={this.onDeleteCancel}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default EducationInformation
